package com.kly.cashmall.utils.data;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.Iterator;

/**
 * Created by zxp on 2021/9/14 0014
 */
public class ObjectUtils {
    public static JsonObject toJsonObject(JSONObject jsonObject) {
        JsonObject object = new JsonObject();
        if (jsonObject == null) {
            return object;
        }
        Iterator<String> iterator = jsonObject.keys();
        while (iterator.hasNext()) {
            String key = iterator.next();
            Object value = jsonObject.opt(key);

            if (value instanceof JSONArray) {
                object.add(key, toJsonArray((JSONArray) value));
            } else if (value instanceof JSONObject) {
                object.add(key, toJsonObject((JSONObject) value));
            } else if (value instanceof JsonElement) {
                object.add(key, (JsonElement) value);
            } else if (value instanceof Number) {
                object.addProperty(key, (Number) value);
            } else if (value instanceof Boolean) {
                object.addProperty(key, (Boolean) value);
            } else if (value instanceof Character) {
                object.addProperty(key, (Character) value);
            } else if (value != null) {
                object.addProperty(key, String.valueOf(value));
            }
        }
        return object;
    }

    public static JsonArray toJsonArray(JSONArray jsonArray) {
        JsonArray array = new JsonArray();
        if (jsonArray == null) {
            return array;
        }

        for (int i = 0; i < jsonArray.length(); i++) {
            Object value = jsonArray.opt(i);
            if (value instanceof JSONArray) {
                array.add(toJsonArray((JSONArray) value));
            } else if (value instanceof JSONObject) {
                array.add(toJsonObject((JSONObject) value));
            } else if (value instanceof JsonElement) {
                array.add((JsonElement) value);
            } else if (value instanceof Number) {
                array.add((Number) value);
            } else if (value instanceof Boolean) {
                array.add((Boolean) value);
            } else if (value instanceof Character) {
                array.add((Character) value);
            } else if (value != null) {
                array.add(String.valueOf(value));
            }
        }

        return array;
    }
}